package com.alibaba.nacos.common.task.engine;

import com.alibaba.nacos.common.task.AbstractExecuteTask;
import com.alibaba.nacos.common.task.NacosTaskProcessor;
import org.springframework.stereotype.Component;

import java.util.Objects;
import java.util.stream.IntStream;


@Component
public class NacosExecuteTaskExecuteEngine
        extends AbstractNacosTaskExecuteEngine<AbstractExecuteTask> {

    private final TaskExecuteWorker[] executeWorkers = IntStream.range(0, 16).mapToObj(x -> new TaskExecuteWorker()).toArray(TaskExecuteWorker[]::new);

    @Override
    public NacosTaskProcessor getProcessor(Object key) {
        return task -> {
            if (task instanceof AbstractExecuteTask executeTask) {
                executeTask.run();
                return true;
            }

            throw new UnsupportedOperationException();
        };
    }

    @Override
    public void addTask(Object key,
                        AbstractExecuteTask executeTask) {
        NacosTaskProcessor processor = getProcessor(key);
        if (processor != null) {
            processor.process(executeTask);
            return;
        }

        int idx = Objects.hashCode(key) & Integer.MAX_VALUE % executeWorkers.length;
        TaskExecuteWorker executeWorker = executeWorkers[idx];
        executeWorker.process(executeTask);
    }
}
